<template>
  <div class="personnel-audit">
    <el-card class="control-card">
      <div class="header-controls">
        <div class="info">
          <h3>
            人员数据审核
            <el-text type="info" size="small" style="margin-left: 20px; font-weight: normal;">
              待审核: {{ statistics.pending }} | 
              已通过: {{ statistics.approved }} | 
              已驳回: {{ statistics.rejected }}
            </el-text>
          </h3>
        </div>
        <div class="actions">
          <el-button @click="() => loadNextRecord(true)" :disabled="!currentRecord || autoAuditing">跳过</el-button>
          <el-button 
            type="warning" 
            @click="handleReprocess" 
            :disabled="!currentRecord || autoAuditing" 
            :loading="reprocessing"
            :icon="RefreshRight"
          >
            重新解析
          </el-button>
          <!--
          <el-button 
            type="primary" 
            @click="handleAIAudit" 
            :disabled="!currentRecord || autoAuditing" 
            :loading="aiAuditing"
            :icon="MagicStick"
          >
            AI审核
          </el-button>
          <el-button 
            v-if="!autoAuditing"
            type="warning" 
            @click="startAutoAudit" 
            :disabled="!currentRecord || statistics.pending === 0"
            :icon="VideoPlay"
          >
            自动审核 ({{ statistics.pending }}条)
          </el-button>
          <el-button 
            v-else
            type="info" 
            @click="stopAutoAudit"
            :icon="VideoPause"
          >
            暂停自动审核
          </el-button>
          -->
          <el-button type="danger" @click="handleReject" :disabled="!currentRecord || autoAuditing" :loading="submitting">
            驳回
          </el-button>
          <el-button type="success" @click="handleApprove" :disabled="!currentRecord || autoAuditing" :loading="submitting">
            通过
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 自动审核进度 -->
    <el-card v-if="autoAuditing" class="auto-audit-progress-card">
      <div class="progress-content">
        <div class="progress-info">
          <div class="progress-title">
            <el-icon class="rotating"><Loading /></el-icon>
            <span>自动审核进行中...</span>
          </div>
          <div class="progress-stats">
            <el-tag type="success">已完成: {{ autoAuditStats.completed }}</el-tag>
            <el-tag type="info">剩余: {{ autoAuditStats.remaining }}</el-tag>
            <el-tag type="warning" v-if="autoAuditStats.modified > 0">已修正: {{ autoAuditStats.modified }}</el-tag>
            <el-tag type="danger" v-if="autoAuditStats.errors > 0">错误: {{ autoAuditStats.errors }}</el-tag>
          </div>
        </div>
        <div class="progress-bar">
          <el-progress 
            :percentage="autoAuditProgress" 
            :stroke-width="20"
            :color="progressColor"
          >
            <template #default="{ percentage }">
              <span class="progress-text">{{ percentage }}%</span>
            </template>
          </el-progress>
        </div>
        <div class="progress-current" v-if="currentRecord">
          <el-text type="info" size="small">
            正在处理: {{ currentRecord.processed.chinese_name || currentRecord.processed.english_name }}
          </el-text>
        </div>
      </div>
    </el-card>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="12" animated />
    </div>

    <el-empty v-else-if="!currentRecord" description="暂无待审核记录" :image-size="200" />

    <div v-else class="audit-content">
      <!-- 左侧：原始数据和简介 -->
      <el-card class="left-panel">
        <template #header>
          <div class="card-header">
            <span>原始数据</span>
            <el-tag type="info" size="small">ID: {{ currentRecord.raw.id }}</el-tag>
          </div>
        </template>

        <!-- 头像和基本信息 - 左右布局 -->
        <div class="avatar-section">
          <div class="left-info">
            <el-avatar 
              :size="80" 
              :src="getAvatarUrl(currentRecord.processed?.avatar_path || currentRecord.raw.avatar_url)" 
              fit="cover"
            >
              <el-icon :size="40"><User /></el-icon>
            </el-avatar>
            <h3 class="person-name">{{ currentRecord.raw.name }}</h3>
          </div>
          <div class="right-info">
            <div class="info-item">
              <span class="info-label">岗位：</span>
              <span class="info-value">{{ currentRecord.raw.position || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">军衔：</span>
              <span class="info-value">{{ currentRecord.raw.rank || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">数据源：</span>
              <span class="info-value">{{ currentRecord.raw.data_source || '-' }}</span>
            </div>
          </div>
        </div>

        <el-divider content-position="left">中文简介</el-divider>
        <div class="biography-box markdown-content" v-html="renderMarkdown(currentRecord.processed?.chinese_biography)"></div>

        <el-divider content-position="left">英文简介</el-divider>
        <div class="biography-box markdown-content" v-html="renderMarkdown(currentRecord.processed?.english_biography || currentRecord.raw.biography)"></div>
      </el-card>

      <!-- 右侧：处理后的可编辑数据 -->
      <el-card class="right-panel">
        <template #header>
          <div class="card-header">
            <span>处理后数据（可编辑）</span>
            <el-button text type="primary" size="small" @click="resetForm">
              <el-icon><RefreshLeft /></el-icon> 重置
            </el-button>
          </div>
        </template>

        <el-form
          ref="formRef"
          :model="editForm"
          label-width="100px"
          size="small"
          class="edit-form"
        >
          <div class="form-content">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="中文名">
                    <el-input v-model="editForm.chinese_name" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="英文名">
                    <el-input v-model="editForm.english_name" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="国家/地区">
                    <el-select v-model="editForm.country_region" placeholder="请选择" style="width: 100%" filterable allow-create>
                      <el-option label="美国" value="美国" />
                      <el-option label="日本" value="日本" />
                      <el-option label="印度" value="印度" />
                      <el-option label="韩国" value="韩国" />
                      <el-option label="菲律宾" value="菲律宾" />
                      <el-option label="越南" value="越南" />
                      <el-option label="台湾" value="台湾" />
                      <el-option label="中国" value="中国" />
                      <el-option label="俄罗斯" value="俄罗斯" />
                      <el-option label="英国" value="英国" />
                      <el-option label="法国" value="法国" />
                      <el-option label="德国" value="德国" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="性别">
                    <el-select v-model="editForm.gender" placeholder="请选择" style="width: 100%">
                      <el-option label="男" value="male" />
                      <el-option label="女" value="female" />
                      <el-option label="未知" value="unknown" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="出生日期">
                    <el-input
                      v-model="editForm.birth_date"
                      placeholder="格式：YYYY 或 YYYY-MM 或 YYYY-MM-DD"
                      clearable
                    >
                      <template #append>
                        <el-text type="info" size="small">支持多种精度</el-text>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="年龄">
                    <el-input-number v-model="editForm.age" :min="0" :max="150" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="邮箱">
                    <el-input v-model="editForm.email" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="电话">
                    <el-input v-model="editForm.phone" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="毕业院校">
                    <el-input v-model="editForm.graduate_school" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="学历">
                    <el-input v-model="editForm.education_level" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="军兵种">
                    <el-select v-model="editForm.military_branch" placeholder="请选择" style="width: 100%" filterable allow-create>
                      <el-option label="陆军" value="陆军" />
                      <el-option label="海军" value="海军" />
                      <el-option label="空军" value="空军" />
                      <el-option label="太空军" value="太空军" />
                      <el-option label="海军陆战队" value="海军陆战队" />
                      <el-option label="联合部队" value="联合部队" />
                      <el-option label="战略支援部队" value="战略支援部队" />
                      <el-option label="特种作战部队" value="特种作战部队" />
                      <el-option label="网络空间部队" value="网络空间部队" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="军衔">
                    <el-input v-model="editForm.military_rank" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="所在机构">
                    <el-input v-model="editForm.organization" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="当前职务">
                    <el-input v-model="editForm.current_position" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="任职日期">
                    <el-input
                      v-model="editForm.position_start_date"
                      placeholder="格式：YYYY 或 YYYY-MM 或 YYYY-MM-DD"
                      clearable
                    >
                      <template #append>
                        <el-text type="info" size="small">支持多种精度</el-text>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="工作状态">
                    <el-input v-model="editForm.work_status" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="数据来源">
                    <el-input v-model="editForm.data_source" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="源数据ID">
                    <el-input v-model="editForm.source_data_id" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="教育经历">
                <el-input
                  v-model="editForm.education_experience_cn"
                  type="textarea"
                  :rows="5"
                  placeholder="教育经历（中文）"
                />
              </el-form-item>
              <el-form-item label="工作经历">
                <el-input
                  v-model="editForm.work_experience_cn"
                  type="textarea"
                  :rows="5"
                  placeholder="工作经历（中文）"
                />
              </el-form-item>
            </div>
        </el-form>
      </el-card>
    </div>

    <!-- 审核意见对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      :title="auditType === 'approved' ? '审核通过' : '审核驳回'"
      width="600px"
    >
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="审核人">
          <el-text>{{ userStore.userInfo?.realName }} ({{ userStore.userInfo?.employeeId }})</el-text>
        </el-form-item>
        
        <!-- 驳回时显示常用原因 -->
        <el-form-item v-if="auditType === 'rejected'" label="常用原因">
          <div class="reject-reasons">
            <el-tag
              v-for="reason in commonRejectReasons"
              :key="reason"
              class="reason-tag"
              @click="selectRejectReason(reason)"
              style="cursor: pointer"
            >
              {{ reason }}
            </el-tag>
          </div>
        </el-form-item>
        
        <el-form-item :label="auditType === 'rejected' ? '驳回原因' : '审核意见'" :required="auditType === 'rejected'">
          <el-input
            v-model="auditForm.comment"
            type="textarea"
            :rows="4"
            :placeholder="auditType === 'rejected' ? '请输入驳回原因或点击上方常用原因快速填充' : '请输入审核意见（选填）'"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit" :loading="submitting">
          提交
        </el-button>
      </template>
    </el-dialog>

    <!-- AI审核结果抽屉 -->
    <el-drawer
      v-model="aiAuditDrawerVisible"
      title="AI审核结果"
      size="50%"
      direction="rtl"
      :close-on-click-modal="false"
    >
      <div v-if="aiAuditResult" class="ai-audit-result">
        <!-- 整体评分和建议 -->
        <el-card shadow="never" class="summary-card">
          <div class="score-section">
            <div class="score-circle">
              <el-progress
                type="circle"
                :percentage="aiAuditResult.overall_score"
                :width="120"
                :color="getScoreColor(aiAuditResult.overall_score)"
              >
                <template #default="{ percentage }">
                  <span class="score-text">{{ percentage }}分</span>
                </template>
              </el-progress>
            </div>
            <div class="recommendation-section">
              <div class="recommendation-label">审核建议：</div>
              <el-tag
                :type="getRecommendationType(aiAuditResult.recommendation)"
                size="large"
                effect="dark"
              >
                {{ aiAuditResult.recommendation }}
              </el-tag>
            </div>
          </div>
          <el-divider />
          <div class="summary-text">
            <strong>总结：</strong>{{ aiAuditResult.summary }}
          </div>
        </el-card>

        <!-- 准确的字段 -->
        <el-card shadow="never" class="fields-card" v-if="aiAuditResult.accurate_fields && aiAuditResult.accurate_fields.length > 0">
          <template #header>
            <span><el-icon color="#67c23a"><CircleCheck /></el-icon> 准确的字段 ({{ aiAuditResult.accurate_fields.length }})</span>
          </template>
          <el-tag
            v-for="field in aiAuditResult.accurate_fields"
            :key="field"
            type="success"
            size="small"
            class="field-tag"
          >
            {{ field }}
          </el-tag>
        </el-card>

        <!-- 不准确的字段 -->
        <el-card shadow="never" class="fields-card" v-if="aiAuditResult.inaccurate_fields && aiAuditResult.inaccurate_fields.length > 0">
          <template #header>
            <div class="card-header-with-action">
              <span><el-icon color="#f56c6c"><CircleClose /></el-icon> 不准确的字段 ({{ aiAuditResult.inaccurate_fields.length }})</span>
              <el-button 
                type="warning" 
                size="small" 
                @click="applyAllCorrections"
                :icon="RefreshLeft"
              >
                一键修正全部
              </el-button>
            </div>
          </template>
          <div
            v-for="(item, index) in aiAuditResult.inaccurate_fields"
            :key="index"
            class="inaccurate-item"
          >
            <div class="item-header">
              <el-tag type="danger" size="small">{{ item.field }}</el-tag>
              <el-button 
                type="primary" 
                size="small" 
                text
                @click="applySingleCorrection(item)"
              >
                应用修正
              </el-button>
            </div>
            <div class="item-content">
              <div class="item-row">
                <span class="label">提取的值：</span>
                <span class="value error-value">{{ item.extracted || '[空]' }}</span>
              </div>
              <div class="item-row">
                <span class="label">应该是：</span>
                <span class="value correct-value">{{ item.should_be }}</span>
              </div>
              <div class="item-row">
                <span class="label">原因：</span>
                <span class="value">{{ item.reason }}</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 需要关注的问题 -->
        <el-card shadow="never" class="fields-card" v-if="aiAuditResult.issues && aiAuditResult.issues.length > 0">
          <template #header>
            <span><el-icon color="#e6a23c"><Warning /></el-icon> 需要关注的问题 ({{ aiAuditResult.issues.length }})</span>
          </template>
          <el-alert
            v-for="(issue, index) in aiAuditResult.issues"
            :key="index"
            :title="issue"
            type="warning"
            :closable="false"
            show-icon
            class="issue-alert"
          />
        </el-card>
      </div>

      <template #footer>
        <div class="drawer-footer">
          <el-button @click="aiAuditDrawerVisible = false">关闭</el-button>
          <el-button 
            v-if="aiAuditResult && aiAuditResult.inaccurate_fields && aiAuditResult.inaccurate_fields.length > 0"
            type="warning" 
            @click="applyAllCorrections"
          >
            应用全部修正
          </el-button>
          <el-button 
            v-if="aiAuditResult"
            type="primary" 
            @click="applyAIRecommendation"
          >
            {{ getRecommendationButtonText(aiAuditResult.recommendation) }}
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, RefreshLeft, RefreshRight, MagicStick, CircleCheck, CircleClose, Warning, VideoPlay, VideoPause, Loading } from '@element-plus/icons-vue'
import { personnelApi } from '@/api/personnel'
import { marked } from 'marked'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 配置marked
marked.setOptions({
  breaks: true, // 支持GFM换行
  gfm: true, // 启用GitHub风格的Markdown
})

// 高亮学历关键词
const highlightEducationKeywords = (html) => {
  if (!html) return html
  
  // 定义需要高亮的关键词
  const keywords = ['学士', '硕士', '博士', '学位']
  
  // 对每个关键词进行高亮处理
  // 使用正则表达式确保不会重复高亮已经被高亮的内容
  let result = html
  keywords.forEach(keyword => {
    // 匹配关键词，但排除已经在HTML标签中的情况
    const regex = new RegExp(`(?<!<[^>]*)(?<!<mark[^>]*>)(${keyword})(?![^<]*>)(?![^<]*</mark>)`, 'g')
    result = result.replace(regex, '<mark class="education-keyword">$1</mark>')
  })
  
  return result
}

// 渲染Markdown
const renderMarkdown = (content) => {
  if (!content) return '<p style="color: #909399;">无</p>'
  try {
    const html = marked.parse(content)
    // 对渲染后的HTML进行关键词高亮
    return highlightEducationKeywords(html)
  } catch (error) {
    console.error('Markdown渲染失败:', error)
    return `<p>${content}</p>`
  }
}

const loading = ref(false)
const submitting = ref(false)
const reprocessing = ref(false)
const currentRecord = ref(null)
const auditDialogVisible = ref(false)
const auditType = ref('approved') // 'approved' | 'rejected'
const skippedRecordIds = ref(new Set()) // 记录跳过的记录ID

// AI审核相关
const aiAuditing = ref(false)
const aiAuditDrawerVisible = ref(false)
const aiAuditResult = ref(null)

// 自动审核相关
const autoAuditing = ref(false)
const autoAuditStopping = ref(false)
const autoAuditStats = reactive({
  total: 0,
  completed: 0,
  remaining: 0,
  modified: 0,
  errors: 0
})

// 自动审核进度
const autoAuditProgress = computed(() => {
  if (autoAuditStats.total === 0) return 0
  return Math.round((autoAuditStats.completed / autoAuditStats.total) * 100)
})

const statistics = reactive({
  pending: 0,
  approved: 0,
  rejected: 0
})

const editForm = reactive({
  chinese_name: '',
  english_name: '',
  country_region: '',
  gender: '',
  birth_date: '',
  age: null,
  email: '',
  phone: '',
  graduate_school: '',
  education_level: '',
  military_branch: '',
  military_rank: '',
  organization: '',
  current_position: '',
  position_start_date: '',
  work_status: '',
  work_experience_cn: '',
  education_experience_cn: '',
  data_source: '',
  source_data_id: ''
})

const auditForm = reactive({
  comment: ''
})

// 常用驳回原因
const commonRejectReasons = [
  '已退役',
  '信息不完整',
  '数据有误',
  '重复记录',
  '非现役人员',
  '缺少关键信息',
  '翻译错误',
  '职务信息错误',
  '已去世'
]

// 选择驳回原因
const selectRejectReason = (reason) => {
  if (auditForm.comment) {
    auditForm.comment += '；' + reason
  } else {
    auditForm.comment = reason
  }
}

// 获取头像URL
const getAvatarUrl = (path) => {
  if (!path) return ''
  // 如果是完整URL，直接返回
  if (path.startsWith('http://') || path.startsWith('https://')) {
    return path
  }
  // 处理本地路径
  // 统一使用正斜杠
  let normalizedPath = path.replace(/\\/g, '/')
  
  // 如果路径已经以uploads/avatars/开头，添加前导斜杠
  if (normalizedPath.startsWith('uploads/avatars/')) {
    return '/' + normalizedPath
  }
  
  // 如果路径以./uploads开头，去掉./
  if (normalizedPath.startsWith('./uploads')) {
    return normalizedPath.substring(1)
  }
  
  // 其他情况，确保有前导斜杠
  return normalizedPath.startsWith('/') ? normalizedPath : '/' + normalizedPath
}

// 加载统计数据
const loadStatistics = async () => {
  try {
    const data = await personnelApi.getAuditStatistics()
    Object.assign(statistics, data)
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载下一条待审核记录
const loadNextRecord = async (skipCurrent = false) => {
  loading.value = true
  try {
    // 如果是跳过操作，记录当前记录ID
    if (skipCurrent && currentRecord.value) {
      skippedRecordIds.value.add(currentRecord.value.raw.id)
    }
    
    // 获取更多记录以便筛选（获取20条，找到第一条未跳过的）
    const data = await personnelApi.getPendingAudit({ page: 1, pageSize: 20 })
    if (data.list && data.list.length > 0) {
      // 找到第一条未跳过的记录
      const nextRecord = data.list.find(record => !skippedRecordIds.value.has(record.id))
      
      if (nextRecord) {
        // 获取详细信息
        const detail = await personnelApi.getAuditDetail(nextRecord.id)
        currentRecord.value = {
          raw: detail.rawRecord,
          processed: detail.processedRecord
        }
        // 填充表单
        resetForm()
      } else {
        // 所有获取到的记录都被跳过了
        if (data.list.length < data.total) {
          // 还有更多记录，清空跳过列表重新开始
          skippedRecordIds.value.clear()
          ElMessage.info('已浏览所有记录，重新开始')
          await loadNextRecord()
        } else {
          // 真的没有记录了
          currentRecord.value = null
          ElMessage.success('所有记录已审核完成！')
        }
      }
    } else {
      currentRecord.value = null
      skippedRecordIds.value.clear()
      ElMessage.success('所有记录已审核完成！')
    }
  } catch (error) {
    console.error('加载记录失败:', error)
    ElMessage.error('加载记录失败')
  } finally {
    loading.value = false
  }
}

// 重置表单（从processed数据填充）
const resetForm = () => {
  if (!currentRecord.value?.processed) return
  
  const p = currentRecord.value.processed
  Object.assign(editForm, {
    chinese_name: p.chinese_name || '',
    english_name: p.english_name || '',
    country_region: p.country_region || '',
    gender: p.gender || '',
    birth_date: p.birth_date || '',
    age: p.age || null,
    email: p.email || '',
    phone: p.phone || '',
    graduate_school: p.graduate_school || '',
    education_level: p.education_level || '',
    military_branch: p.military_branch || '',
    military_rank: p.military_rank || '',
    organization: p.organization || '',
    current_position: p.current_position || '',
    position_start_date: p.position_start_date || '',
    work_status: p.work_status || '',
    work_experience_cn: p.work_experience_cn || '',
    education_experience_cn: p.education_experience_cn || '',
    data_source: p.data_source || '',
    source_data_id: p.source_data_id || ''
  })
}

// 处理通过
const handleApprove = () => {
  auditType.value = 'approved'
  auditDialogVisible.value = true
}

// 处理驳回
const handleReject = () => {
  auditType.value = 'rejected'
  auditDialogVisible.value = true
}

// 提交审核
const submitAudit = async () => {
  if (auditType.value === 'rejected' && !auditForm.comment) {
    ElMessage.warning('驳回时必须填写原因')
    return
  }

  submitting.value = true
  try {
    // 提交审核结果，包含编辑后的数据
    // 审核人信息将由后端自动从token中获取
    await personnelApi.submitAudit({
      rawPersonnelId: currentRecord.value.raw.id,
      auditStatus: auditType.value,
      comment: auditForm.comment,
      // 附带修改后的数据
      updatedData: editForm
    })

    ElMessage.success(auditType.value === 'approved' ? '审核通过' : '已驳回')
    
    auditDialogVisible.value = false
    
    // 清空审核表单
    auditForm.comment = ''
    
    // 审核后清空跳过列表（因为列表已更新）
    skippedRecordIds.value.clear()
    
    // 更新统计
    await loadStatistics()
    
    // 加载下一条
    await loadNextRecord(false)
  } catch (error) {
    console.error('提交审核失败:', error)
    ElMessage.error(error.response?.data?.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 重新解析
const handleReprocess = async () => {
  if (!currentRecord.value) return

  try {
    const result = await ElMessageBox.confirm(
      '将根据该记录的原始数据重新进行完整的数据处理和解析，包括AI提取、翻译等步骤。这将覆盖当前的所有处理后数据，是否继续？',
      '重新解析数据',
      {
        confirmButtonText: '确认重新解析',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (result === 'confirm') {
      reprocessing.value = true
      
      ElMessage.info('开始重新解析，请稍候...')

      const response = await personnelApi.reprocessRecord(currentRecord.value.raw.id)
      
      if (response.success) {
        ElMessage.success('重新解析成功！数据已更新')
        
        // 重新加载当前记录的详情
        const detail = await personnelApi.getAuditDetail(currentRecord.value.raw.id)
        currentRecord.value = {
          raw: detail.rawRecord,
          processed: detail.processedRecord
        }
        // 刷新表单
        resetForm()
      } else {
        throw new Error(response.message || '重新解析失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重新解析失败: ' + (error.response?.data?.message || error.message))
    }
  } finally {
    reprocessing.value = false
  }
}

// AI审核
const handleAIAudit = async () => {
  if (!currentRecord.value) return

  aiAuditing.value = true
  try {
    const result = await personnelApi.aiAudit(currentRecord.value.raw.id)
    
    if (result.success) {
      aiAuditResult.value = result
      aiAuditDrawerVisible.value = true
      ElMessage.success('AI审核完成')
    }
  } catch (error) {
    console.error('AI审核失败:', error)
    ElMessage.error('AI审核失败: ' + (error.response?.data?.message || error.message))
  } finally {
    aiAuditing.value = false
  }
}

// 获取评分颜色
const getScoreColor = (score) => {
  if (score >= 90) return '#67c23a'
  if (score >= 70) return '#409eff'
  if (score >= 50) return '#e6a23c'
  return '#f56c6c'
}

// 获取建议类型
const getRecommendationType = (recommendation) => {
  const map = {
    '通过': 'success',
    '需要修改': 'warning',
    '驳回': 'danger'
  }
  return map[recommendation] || 'info'
}

// 获取建议按钮文本
const getRecommendationButtonText = (recommendation) => {
  if (!recommendation) return '采纳建议'
  
  const map = {
    '通过': '采纳建议并通过',
    '需要修改': '仅关闭（需手动修改）',
    '驳回': '采纳建议并驳回'
  }
  return map[recommendation] || '采纳建议'
}

// 字段名映射（中文 -> 英文字段名）
const fieldNameMap = {
  '中文姓名': 'chinese_name',
  '英文姓名': 'english_name',
  '性别': 'gender',
  '出生日期': 'birth_date',
  '年龄': 'age',
  '邮箱': 'email',
  '电话': 'phone',
  '毕业院校': 'graduate_school',
  '最高学历': 'education_level',
  '军兵种': 'military_branch',
  '军衔': 'military_rank',
  '所在机构': 'organization',
  '当前职务': 'current_position',
  '任职日期': 'position_start_date',
  '工作状态': 'work_status'
}

// 应用单个字段修正
const applySingleCorrection = (item) => {
  const fieldKey = fieldNameMap[item.field]
  if (fieldKey && editForm[fieldKey] !== undefined) {
    editForm[fieldKey] = item.should_be
    ElMessage.success(`已修正"${item.field}"`)
  } else {
    ElMessage.warning(`无法识别字段"${item.field}"`)
  }
}

// 应用所有修正
const applyAllCorrections = () => {
  if (!aiAuditResult.value?.inaccurate_fields?.length) return
  
  let count = 0
  aiAuditResult.value.inaccurate_fields.forEach(item => {
    const fieldKey = fieldNameMap[item.field]
    if (fieldKey && editForm[fieldKey] !== undefined) {
      editForm[fieldKey] = item.should_be
      count++
    }
  })
  
  ElMessage.success(`已修正 ${count} 个字段`)
  
  // 关闭抽屉，让用户查看修正后的数据
  aiAuditDrawerVisible.value = false
}

// 采纳AI建议
const applyAIRecommendation = () => {
  if (!aiAuditResult.value) return

  const recommendation = aiAuditResult.value.recommendation
  
  if (recommendation === '通过') {
    // 先应用所有修正，然后通过
    if (aiAuditResult.value.inaccurate_fields?.length > 0) {
      applyAllCorrections()
      ElMessage.success('已应用AI修正，请检查后提交通过')
    } else {
      aiAuditDrawerVisible.value = false
      handleApprove()
    }
  } else if (recommendation === '驳回') {
    aiAuditDrawerVisible.value = false
    // 自动填充审核意见
    auditForm.comment = aiAuditResult.value.summary || 'AI审核建议驳回'
    handleReject()
  } else {
    // 需要修改：只关闭抽屉
    aiAuditDrawerVisible.value = false
    ElMessage.info('请手动修改数据后再提交')
  }
}

// 自动审核功能
const startAutoAudit = async () => {
  try {
    const result = await ElMessageBox.confirm(
      `将自动审核所有待审核记录（共${statistics.pending}条）。AI会自动分析、修正并通过符合条件的记录。是否继续？`,
      '开始自动审核',
      {
        confirmButtonText: '开始',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    if (result === 'confirm') {
      autoAuditing.value = true
      autoAuditStopping.value = false
      
      // 初始化统计
      autoAuditStats.total = statistics.pending
      autoAuditStats.completed = 0
      autoAuditStats.remaining = statistics.pending
      autoAuditStats.modified = 0
      autoAuditStats.errors = 0

      ElMessage.success('自动审核已开始')

      // 开始自动审核循环
      await runAutoAuditLoop()
    }
  } catch {
    // 用户取消
  }
}

const stopAutoAudit = () => {
  autoAuditStopping.value = true
  ElMessage.info('正在停止自动审核...')
}

const runAutoAuditLoop = async () => {
  while (autoAuditing.value && !autoAuditStopping.value) {
    // 检查是否还有待审核记录
    if (!currentRecord.value || statistics.pending === 0) {
      break
    }

    try {
      const personName = currentRecord.value.processed.chinese_name || currentRecord.value.processed.english_name
      console.log(`\n${'='.repeat(60)}`)
      console.log(`🔍 自动审核 [${autoAuditStats.completed + 1}/${autoAuditStats.total}]: ${personName}`)
      console.log(`   记录ID: ${currentRecord.value.raw.id}`)
      console.log(`${'='.repeat(60)}`)
      
      // 1. 调用AI审核
      console.log('📋 步骤1: 调用AI审核...')
      aiAuditing.value = true
      const auditResult = await personnelApi.aiAudit(currentRecord.value.raw.id)
      aiAuditing.value = false

      if (!auditResult.success) {
        throw new Error('AI审核失败')
      }

      console.log(`✓ AI审核完成`)
      console.log(`   评分: ${auditResult.overall_score}/100`)
      console.log(`   建议: ${auditResult.recommendation}`)
      console.log(`   准确字段: ${auditResult.accurate_fields?.length || 0}个`)
      console.log(`   不准确字段: ${auditResult.inaccurate_fields?.length || 0}个`)
      console.log(`   需要关注: ${auditResult.issues?.length || 0}个问题`)
      if (auditResult.summary) {
        console.log(`   摘要: ${auditResult.summary}`)
      }

      // 2. 应用修正（如果有不准确的字段）
      let hasModifications = false
      let modificationCount = 0
      
      if (auditResult.inaccurate_fields && auditResult.inaccurate_fields.length > 0) {
        console.log(`\n🔧 步骤2: 应用字段修正（共${auditResult.inaccurate_fields.length}个）`)
        
        auditResult.inaccurate_fields.forEach((item, index) => {
          const fieldKey = fieldNameMap[item.field]
          if (fieldKey && editForm[fieldKey] !== undefined) {
            console.log(`   ${index + 1}. ${item.field}:`)
            console.log(`      原值: "${item.extracted}"`)
            console.log(`      新值: "${item.should_be}"`)
            if (item.reason) {
              console.log(`      原因: ${item.reason}`)
            }
            editForm[fieldKey] = item.should_be
            hasModifications = true
            modificationCount++
          } else {
            console.warn(`   ⚠️  无法识别字段"${item.field}"，跳过修正`)
          }
        })
        
        if (hasModifications) {
          autoAuditStats.modified++
          console.log(`✓ 已修正 ${modificationCount} 个字段`)
        }
      } else {
        console.log(`\n✓ 步骤2: 无需修正（所有字段准确）`)
      }
      
      // 显示需要关注的问题
      if (auditResult.issues && auditResult.issues.length > 0) {
        console.log(`\n⚠️  需要关注的问题:`)
        auditResult.issues.forEach((issue, index) => {
          console.log(`   ${index + 1}. ${issue}`)
        })
      }

      // 3. 根据AI建议决定操作
      console.log(`\n📝 步骤3: 决定审核操作`)
      
      if (auditResult.recommendation === '通过' || auditResult.overall_score >= 90) {
        // 自动通过
        console.log(`   决策: 自动通过 ✅`)
        console.log(`   理由: 评分${auditResult.overall_score}分，建议"${auditResult.recommendation}"`)
        if (hasModifications) {
          console.log(`   修正: 已自动修正${modificationCount}个字段`)
        }
        
        const comment = hasModifications 
          ? `AI审核通过（已自动修正${modificationCount}个字段）` 
          : 'AI审核通过'
        
        console.log(`   备注: ${comment}`)
        
        await personnelApi.submitAudit({
          rawPersonnelId: currentRecord.value.raw.id,
          auditStatus: 'approved',
          comment,
          updatedData: editForm
        })
        
        autoAuditStats.completed++
        autoAuditStats.remaining--
        console.log(`✓ 已提交审核结果（通过）`)
        
      } else if (auditResult.recommendation === '驳回' || auditResult.overall_score < 60) {
        // 自动驳回
        console.log(`   决策: 自动驳回 ❌`)
        console.log(`   理由: 评分${auditResult.overall_score}分，建议"${auditResult.recommendation}"`)
        console.log(`   问题: ${auditResult.summary || '数据质量不符合要求'}`)
        
        const comment = auditResult.summary || 'AI审核建议驳回：数据质量不符合要求'
        console.log(`   备注: ${comment}`)
        
        await personnelApi.submitAudit({
          rawPersonnelId: currentRecord.value.raw.id,
          auditStatus: 'rejected',
          comment,
          updatedData: editForm
        })
        
        autoAuditStats.completed++
        autoAuditStats.remaining--
        console.log(`✓ 已提交审核结果（驳回）`)
        
      } else {
        // 需要修改：应用修正后通过
        console.log(`   决策: 修正后通过 ⚠️`)
        console.log(`   理由: 评分${auditResult.overall_score}分（60-89分区间）`)
        console.log(`   修正: 已修正${modificationCount}个字段`)
        
        const comment = hasModifications 
          ? `AI审核（已修正${modificationCount}个字段）：${auditResult.summary}` 
          : `AI审核：${auditResult.summary}`
        console.log(`   备注: ${comment}`)
        
        await personnelApi.submitAudit({
          rawPersonnelId: currentRecord.value.raw.id,
          auditStatus: 'approved',
          comment,
          updatedData: editForm
        })
        
        autoAuditStats.completed++
        autoAuditStats.remaining--
        console.log(`✓ 已提交审核结果（修正后通过）`)
      }

      // 4. 统计和进度
      console.log(`\n📊 当前进度统计:`)
      console.log(`   已完成: ${autoAuditStats.completed}/${autoAuditStats.total}`)
      console.log(`   已修正: ${autoAuditStats.modified}条`)
      console.log(`   错误数: ${autoAuditStats.errors}条`)
      console.log(`   剩余: ${autoAuditStats.remaining}条`)
      
      // 5. 更新统计
      console.log(`\n🔄 更新统计数据...`)
      await loadStatistics()

      // 6. 加载下一条记录
      console.log(`📄 加载下一条记录...`)
      await loadNextRecord(false)

      console.log(`${'='.repeat(60)}\n`)

      // 7. 短暂延迟，避免请求过快
      await new Promise(resolve => setTimeout(resolve, 500))

    } catch (error) {
      const personName = currentRecord.value?.processed?.chinese_name || currentRecord.value?.processed?.english_name || '未知'
      console.error(`\n${'!'.repeat(60)}`)
      console.error(`❌ 自动审核出错: ${personName}`)
      console.error(`   错误信息: ${error.message}`)
      console.error(`   错误详情:`, error)
      console.error(`${'!'.repeat(60)}\n`)
      
      autoAuditStats.errors++
      
      // 跳过当前记录，继续下一条
      console.log(`⏭️  跳过当前记录，继续下一条...`)
      await loadNextRecord(false)
      await new Promise(resolve => setTimeout(resolve, 500))
    }
  }

  // 审核完成
  console.log(`\n${'='.repeat(60)}`)
  console.log(`🎉 自动审核全部完成！`)
  console.log(`${'='.repeat(60)}`)
  console.log(`📊 最终统计:`)
  console.log(`   总计: ${autoAuditStats.total}条`)
  console.log(`   完成: ${autoAuditStats.completed}条`)
  console.log(`   修正: ${autoAuditStats.modified}条（有修正的记录数）`)
  console.log(`   错误: ${autoAuditStats.errors}条`)
  console.log(`   成功率: ${autoAuditStats.total > 0 ? ((autoAuditStats.completed / autoAuditStats.total) * 100).toFixed(1) : 0}%`)
  console.log(`${'='.repeat(60)}\n`)

  autoAuditing.value = false
  autoAuditStopping.value = false

  if (autoAuditStats.completed > 0) {
    ElMessage.success({
      message: `自动审核完成！共处理${autoAuditStats.completed}条记录，修正${autoAuditStats.modified}条，错误${autoAuditStats.errors}条`,
      duration: 5000
    })
  }
}

onMounted(() => {
  loadStatistics()
  loadNextRecord()
})

// 组件卸载时停止自动审核
onBeforeUnmount(() => {
  if (autoAuditing.value) {
    autoAuditStopping.value = true
  }
})
</script>

<style lang="scss" scoped>
.personnel-audit {
  .control-card {
    margin-bottom: 20px;

    :deep(.el-card__body) {
      padding: 15px 20px;  // 减少上下padding
    }

    .header-controls {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .info {
        h3 {
          margin: 0;
          display: flex;
          align-items: center;
        }
      }

      .actions {
        display: flex;
        gap: 10px;
      }
    }
  }

  .auto-audit-progress-card {
    margin-bottom: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;

    :deep(.el-card__body) {
      padding: 20px;
    }

    .progress-content {
      .progress-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .progress-title {
          display: flex;
          align-items: center;
          gap: 12px;
          font-size: 18px;
          font-weight: 600;

          .el-icon {
            font-size: 24px;

            &.rotating {
              animation: rotate 2s linear infinite;
            }
          }
        }

        .progress-stats {
          display: flex;
          gap: 12px;

          .el-tag {
            font-weight: 600;
          }
        }
      }

      .progress-bar {
        margin-bottom: 12px;

        :deep(.el-progress__text) {
          color: white !important;
          font-weight: 600;
        }

        .progress-text {
          font-size: 14px;
        }
      }

      .progress-current {
        text-align: center;
        opacity: 0.9;
      }
    }
  }

  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  .loading-container {
    padding: 20px;
  }

  .audit-content {
    display: grid;
    grid-template-columns: 40% 1fr;
    gap: 20px;
    align-items: stretch;  // 改为拉伸填充
    height: calc(100vh - 200px);  // 设置固定高度

    .left-panel,
    .right-panel {
      display: flex;
      flex-direction: column;
      overflow: hidden;  // 隐藏溢出，让内部滚动
      
      :deep(.el-card__body) {
        flex: 1;
        overflow-y: auto;  // card 内部滚动
        overflow-x: hidden;
      }
    }

    .left-panel {

      .avatar-section {
        display: flex;
        padding: 12px 0;
        gap: 20px;
        align-items: center;

        .left-info {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 8px;
          min-width: 100px;

          .person-name {
            margin: 0;
            font-size: 14px;
            font-weight: 600;
            color: #303133;
            text-align: center;
            word-break: break-word;
          }
        }

        .right-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          gap: 8px;

          .info-item {
            display: flex;
            align-items: center;
            line-height: 1.4;

            .info-label {
              font-size: 13px;
              color: #909399;
              min-width: 60px;
              font-weight: 500;
            }

            .info-value {
              font-size: 13px;
              color: #303133;
              flex: 1;
            }
          }
        }
      }

      .biography-box {
        margin-top: 10px;
        margin-bottom: 10px;
        padding: 12px;
        background-color: #f5f7fa;
        border-radius: 4px;
        flex-shrink: 0;  // 不压缩简介区域

        .biography-text {
          line-height: 1.8;
          color: #606266;
          white-space: pre-wrap;
          word-break: break-word;
        }

        // Markdown内容样式
        &.markdown-content {
          :deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
            margin: 16px 0 8px 0;
            font-weight: 600;
            color: #303133;
            line-height: 1.4;
          }

          :deep(h1) { font-size: 24px; border-bottom: 1px solid #e4e7ed; padding-bottom: 8px; }
          :deep(h2) { font-size: 20px; border-bottom: 1px solid #e4e7ed; padding-bottom: 6px; }
          :deep(h3) { font-size: 18px; }
          :deep(h4) { font-size: 16px; }
          :deep(h5) { font-size: 15px; }
          :deep(h6) { font-size: 14px; color: #606266; }

          :deep(p) {
            margin: 8px 0;
            line-height: 1.8;
            color: #606266;
          }

          :deep(ul), :deep(ol) {
            margin: 8px 0;
            padding-left: 28px;
            color: #606266;
            
            li {
              margin: 4px 0;
              line-height: 1.6;
            }
          }

          :deep(ul) {
            list-style-type: disc;
          }

          :deep(ol) {
            list-style-type: decimal;
          }

          :deep(strong) {
            font-weight: 600;
            color: #303133;
          }

          :deep(em) {
            font-style: italic;
            color: #606266;
          }

          :deep(code) {
            padding: 2px 6px;
            margin: 0 2px;
            background-color: rgba(175, 184, 193, 0.2);
            border-radius: 3px;
            font-family: 'Courier New', Courier, monospace;
            font-size: 13px;
            color: #e83e8c;
          }

          :deep(pre) {
            margin: 12px 0;
            padding: 12px;
            background-color: #282c34;
            border-radius: 4px;
            overflow-x: auto;

            code {
              background: none;
              padding: 0;
              margin: 0;
              color: #abb2bf;
              font-size: 13px;
            }
          }

          :deep(blockquote) {
            margin: 12px 0;
            padding: 8px 16px;
            border-left: 4px solid #409eff;
            background-color: rgba(64, 158, 255, 0.05);
            color: #606266;

            p {
              margin: 4px 0;
            }
          }

          :deep(hr) {
            margin: 16px 0;
            border: none;
            border-top: 1px solid #dcdfe6;
          }

          :deep(a) {
            color: #409eff;
            text-decoration: none;
            
            &:hover {
              text-decoration: underline;
            }
          }

          :deep(table) {
            margin: 12px 0;
            border-collapse: collapse;
            width: 100%;
            
            th, td {
              border: 1px solid #dcdfe6;
              padding: 8px 12px;
              text-align: left;
            }

            th {
              background-color: #f5f7fa;
              font-weight: 600;
              color: #303133;
            }

            td {
              color: #606266;
            }
          }

          // 第一个元素上边距为0
          :deep(*:first-child) {
            margin-top: 0;
          }

          // 最后一个元素下边距为0
          :deep(*:last-child) {
            margin-bottom: 0;
          }

          // 学历关键词高亮样式
          :deep(mark.education-keyword) {
            background-color: #fff3cd;
            color: #856404;
            padding: 2px 4px;
            border-radius: 3px;
            font-weight: 600;
            border-bottom: 2px solid #ffc107;
          }
        }
      }
    }

    .right-panel {
      // 强制设置滚动
      :deep(.el-card__body) {
        max-height: calc(100vh - 240px);
        overflow-y: auto !important;
        overflow-x: hidden;
      }

      .edit-form {
        .form-content {
          padding-right: 20px;
          padding-bottom: 20px;

          // 减少表单项间距，让布局更紧凑
          :deep(.el-form-item) {
            margin-bottom: 16px;  // 从默认的 22px 减少到 16px
          }

          // textarea 表单项保持稍大间距
          :deep(.el-form-item:has(.el-textarea)) {
            margin-bottom: 18px;
          }
        }
      }
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  // 驳回原因标签
  .reject-reasons {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .reason-tag {
      &:hover {
        opacity: 0.8;
        transform: scale(1.05);
        transition: all 0.2s;
      }
    }
  }
}

// AI审核结果样式
.ai-audit-result {
  .summary-card {
    margin-bottom: 20px;
    
    .score-section {
      display: flex;
      align-items: center;
      gap: 40px;
      padding: 20px 0;
      
      .score-circle {
        flex-shrink: 0;
        
        .score-text {
          font-size: 24px;
          font-weight: 600;
          color: #303133;
        }
      }
      
      .recommendation-section {
        flex: 1;
        
        .recommendation-label {
          font-size: 14px;
          color: #606266;
          margin-bottom: 12px;
        }
      }
    }
    
    .summary-text {
      font-size: 14px;
      line-height: 1.8;
      color: #303133;
      
      strong {
        color: #409eff;
      }
    }
  }
  
  .fields-card {
    margin-bottom: 20px;
    
    :deep(.el-card__header) {
      padding: 12px 20px;
      
      .el-icon {
        margin-right: 8px;
        vertical-align: middle;
      }
      
      .card-header-with-action {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
    
    .field-tag {
      margin: 4px 8px 4px 0;
    }
    
    .inaccurate-item {
      padding: 12px;
      margin-bottom: 12px;
      background-color: #fef0f0;
      border-radius: 4px;
      border-left: 4px solid #f56c6c;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;
      }
      
      .item-content {
        .item-row {
          display: flex;
          margin-bottom: 8px;
          font-size: 13px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .label {
            flex-shrink: 0;
            width: 80px;
            color: #606266;
            font-weight: 500;
          }
          
          .value {
            flex: 1;
            color: #303133;
            word-break: break-word;
            
            &.error-value {
              color: #f56c6c;
              text-decoration: line-through;
            }
            
            &.correct-value {
              color: #67c23a;
              font-weight: 600;
            }
          }
        }
      }
    }
    
    .issue-alert {
      margin-bottom: 12px;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.drawer-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

@media (max-width: 1200px) {
  .audit-content {
    grid-template-columns: 1fr !important;
    height: auto !important;

    .left-panel,
    .right-panel {
      height: auto;
    }
  }
}
</style>
